package compiler.ast;

import java.io.PrintStream;

import compiler.tac.BasicBlock;
import compiler.tac.ExitBlock;
import compiler.tac.Instruction.Operator;
import compiler.tac.ThreeAddressCode;

public class Assignment extends Statement {
	Designator designator;
	Expression expression;
	
	public Assignment(Designator desig, Expression expr) {
		this.designator = desig;
		this.expression = expr;
	}

	public void printDotFormat(PrintStream out, String node) {
		out.println(node+" [label=\":=\"];");
		
		out.println(node+"->"+node+"0;");
		designator.printDotFormat(out, node+0);
		
		out.println(node+"->"+node+"1;");
		expression.printDotFormat(out, node+1);
	}

	@Override
	public BasicBlock toThreeAddressCode(ThreeAddressCode tac, BasicBlock prev, ExitBlock exit) {
		String valt = expression.toThreeAddressCode(tac, prev);
		String idxt = designator.toThreeAddressCode(tac, prev);
		if (designator.expression == null) {
			prev.addUnaryInstruction(Operator.Mv, idxt, valt);
		} else {
			prev.addStoreInstruction(idxt, valt);
		}
		return prev;
	}
}
